<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
    <script src="../react.development.js"></script>
    <script src="../react-dom.development.js"></script>
    <title>Document</title>
</head>

<body>
    <div id="root"></div>
    <script type="text/babel">
        /*      function Clock(props) {
                 return <h1>It is {props.date.toLocaleTimeString()}</h1>
             }
             function tick() {
                 ReactDOM.render(<Clock date={new Date()} />, document.getElementById())
             }
             setInterval(tick, 1000) */
        //应该把时钟更新的逻辑放到时钟内部

        class Clock extends React.Component {

            constructor(props) {
                super(props)
                this.state = { date: new Date() }
            }

            tick() {
                console.log("hi"+this)
               this.setState({
                    date: new Date()
                });
            }

            componentDidMount() {
                // 这里要用箭头函数，绑定此时的 component 对象，否则调用 tick 时候 setState方法 找不到 
                this.TimerId = setInterval(()=>this.tick(), 1000);
            }

            componentWillUnmount() {
                clearInterval(this.TimerId)
            }

            render() {
                return <h1>It is time: {this.state.date.toLocaleTimeString()}</h1>
            }

           
        }
        ReactDOM.render(<Clock />, document.getElementById("root"))
    </script>
</body>

</html>